package com.laibatour.generator.entity;

import com.laibatour.generator.utils.PropertieUtils;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class TableFactory {
    static Logger log = Logger.getLogger(TableFactory.class);

    private static final String URL = PropertieUtils.getProperty("datasource.url");
    private static final String NAME = PropertieUtils.getProperty("datasource.username");
    private static final String PASS = PropertieUtils.getProperty("datasource.password");;
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    public static Table loadConfig(String tablename){
        Connection con = null;

        Table config = new Table();
        // 查要生成实体类的表
        try {
            Class.forName(DRIVER);

            String sql = "SHOW FULL COLUMNS FROM "+tablename;
            con = DriverManager.getConnection(URL, NAME, PASS);
            PreparedStatement pStemt = con.prepareStatement(sql);
            ResultSet rs = pStemt.executeQuery();
            List<Field> fields = new ArrayList<Field>();
            while (rs.next()) {
                Field field = new Field();
                field.setColName(rs.getString(1));

                String type = rs.getString(2);
                if(type.contains("(")) {
                    try {
                        String length = type.substring(type.indexOf("(") + 1, type.indexOf(")"));
                        field.setColSize(Integer.parseInt(length));
                    } catch (Exception ignored) {
                    }
                    type = type.substring(0, type.indexOf("("));
                }
                field.setColType(type.toUpperCase());
                field.setNotNull("NO".equalsIgnoreCase(rs.getString(4)));
                field.setDefaultValue(rs.getString(6));
                field.setColComment(rs.getString(9));
                fields.add(field);
                if("DECIMAL".equals(field.getColType()) || "NUMERIC".equals(field.getColType())) {
                    config.setHasMath(true);
                }
                if("DATETIME".equals(field.getColType()) || "DATE".equals(field.getColType()) || "TIME".equals(field.getColType()) || "TIMESTAMP".equals(field.getColType())) {
                    config.setHasTime(true);
                }
            }

            config.setFields(fields);
            config.setTableName(tablename);
            return config;
        } catch (Exception e) {
            log.error("GeneratorCode", e);
        } finally {
            if(con!=null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    log.error("GeneratorCode", e);
                }
            }
        }
        return null;
    }


}
